import { defineStore } from 'pinia'
import request from '@/utils/request'
import useCartStore from './cart'
import { ApiRes } from '@/types/data'
import { CartItem } from '@/types/types/cart'
import { UserInfo } from '@/types/user'
import { setUserInfo, getUserInfo, removeUserInfo } from '@/utils/storage'

export default defineStore('user', {
  state() {
    return {
      userInfo: getUserInfo()
    }
  },
  actions: {
    async reqLogin(account: string, password: string) {
      const res = await request.post<ApiRes<UserInfo>>('/login', { account, password })
      console.log(res.data)
      setUserInfo(res.data.result)
      this.userInfo = res.data.result
    },
    async reqGetCode(mobile: string, type: string) {
      await request.get('/code', { params: { mobile, type } })
    },
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<ApiRes<UserInfo>>('/login/code', {
        mobile,
        code
      })
      // 1. 保存用户信息到 state 中
      this.userInfo = res.data.result
      setUserInfo(res.data.result)
    },
    // 退出登录
    logout() {
      this.userInfo = {} as UserInfo
      removeUserInfo()
      // 清空购物车
      useCartStore().list = [] as CartItem[]
    },

    // qq登录
    async QQLogin(unionId: string) {
      const res = await request.post<ApiRes<UserInfo>>('/login/social', { unionId, source: 6 })
      // console.log(res)
      this.userInfo = res.data.result
      setUserInfo(res.data.result)
    },
    // 绑定qq 验证码
    async reqBindCode(mobile: string) {
      await request.get('/login/social/code', { params: { mobile } })
    },
    // 绑定
    async reqBind(unionId: string, mobile: string, code: string) {
      const res = await request.post<ApiRes<UserInfo>>('/login/social/bind', { unionId, mobile, code })
      console.log(res)
      this.userInfo = res.data.result
      setUserInfo(res.data.result)
    },
    // 注册发送验证码
    async reqRegisterCode(mobile: string) {
      await request.get('/register/code', { params: { mobile } })
    },
    // 完善信息 登录
    async reqRegister(data: any) {
      const res = await request.post<ApiRes<UserInfo>>(`/login/social/${data.openId}/complement`, data)
      console.log(res)
      this.userInfo = res.data.result
      setUserInfo(res.data.result)
    }
  },
  getters: {}
})